Interactive Spatial Analysis on the Web
    
      - Dynamic Mapping: Built with Leaflet, this interactive map integrates spatial data directly into your browser.
- On-the-Fly Analysis: Using PyScript and Shapely, we perform real-time spatial analysis to compute neighboring counties for Texas.
- Scientific Approach: The analysis determines if county boundaries touch, ensuring robust spatial measurements.
- Learn More: For an in-depth discussion on geostatistical predicted surfaces and spatial autocorrelation, check out my detailed post on my old weblog here.
- Web-Based Power: Experience the cutting edge of spatial analysis performed directly on the web.
 
  
  
  
  
  
  
  
  
  
  
import json
from shapely.geometry import shape
from pyscript import display
import statistics
from js import window
try:
    TexCounty = window.TexCounty
except Exception as e:
    display("Error: TexCounty variable not defined. Check your data/TexasCounty.js file.", target="adjOutput")
    raise e
txcounty_dict = TexCounty.to_py()
features = txcounty_dict.get("features", [])
if not features:
    result_str = "No features found in TexCounty data."
else:
    polygons = []
    county_names = []
    for i, feature in enumerate(features):
        if feature.get("geometry"):
            polygons.append(shape(feature.get("geometry")))
            name = feature.get("properties", {}).get("name", f"County {i+1}")
            county_names.append(name)
    def is_neighbor(p1, p2):
        return p1.touches(p2)
    n = len(polygons)
    adj_matrix = [[0] * n for _ in range(n)]
    for i in range(n):
        for j in range(n):
            if i != j and is_neighbor(polygons[i], polygons[j]):
                adj_matrix[i][j] = 1
    num_neighbors = [sum(row) for row in adj_matrix]
    avg_neighbors = sum(num_neighbors) / n if n > 0 else 0
    max_neighbors = max(num_neighbors)
    min_neighbors = min(num_neighbors)
    max_index = num_neighbors.index(max_neighbors)
    min_index = num_neighbors.index(min_neighbors)
    county_max = county_names[max_index]
    county_min = county_names[min_index]
    try:
        mode_neighbors = statistics.mode(num_neighbors)
    except statistics.StatisticsError:
        mode_neighbors = statistics.multimode(num_neighbors)
    result_str = "TexCounty Adjacency Calculation (Scientific Approach):\n"
    result_str += f"Number of counties: {n}\n"
    result_str += f"Average number of neighbors: {avg_neighbors:.2f}\n"
    result_str += f"County with most neighbors: {county_max} ({max_neighbors} neighbors)\n"
    result_str += f"County with least neighbors: {county_min} ({min_neighbors} neighbors)\n"
    result_str += f"Mode of neighbors: {mode_neighbors}\n"
    display(result_str, target="adjOutput")